package com.ggy.babybed.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.ggy.babybed.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 工具类
 */
public class Utility {

    private final static String TAG = "Utility";

    /**
     * 位移动画
     * @param view
     * @param xFrom
     * @param xTo
     * @param yFrom
     * @param yTo
     * @param duration
     */
    public static void translateAnimation(View view, float xFrom, float xTo,
                                          float yFrom, float yTo, long duration) {

        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, xFrom, Animation.RELATIVE_TO_SELF, xTo,
                Animation.RELATIVE_TO_SELF, yFrom, Animation.RELATIVE_TO_SELF, yTo);
        translateAnimation.setFillAfter(false);
        translateAnimation.setDuration(duration);
        view.startAnimation(translateAnimation);
        translateAnimation.startNow();
    }

    private static Toast toast;

    /**
     * 全局系统toast
     */
    public static void showToast(Context context, String content) {
        if (toast == null) {
            toast = new Toast(context);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            View v = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
            ((TextView) v.findViewById(R.id.toast_msg)).setText(content);
            toast.setView(v);
        } else {
            ((TextView) toast.getView().findViewById(R.id.toast_msg)).setText(content);
        }
        toast.show();
    }

    public static void showToast(Context context, int content) {
        if (toast == null) {
            toast = new Toast(context);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            View v = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
            ((TextView) v.findViewById(R.id.toast_msg)).setText(content);
            toast.setView(v);
        } else {
            ((TextView) toast.getView().findViewById(R.id.toast_msg)).setText(content);
        }
        toast.show();
    }

    public static void cancelToast() {
        if (toast != null) {
            toast.cancel();
        }
    }

    /**
     * 获取手机SD卡本应用缓存大小
     *
     * @return Long size
     */
    public static long getAppCacheSize(Context context) {
        long size = 0;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {// 外部存储
            File externalCacheDir = context.getExternalCacheDir();
            File externalFilesDir = context.getExternalFilesDir(null);
            size = getFolderSize(externalCacheDir);
            size = size + getFolderSize(externalFilesDir);
        }
        // 内部存储
        File cacheDir = context.getCacheDir();
        File filesDir = context.getFilesDir();
        size = size + getFolderSize(cacheDir);
        size = size + getFolderSize(filesDir);
        return size;
    }

    /**
     * 清除app缓存
     */
    public static void delAppCache(Context context) {
        cleanInternalCache(context);
        cleanFiles(context);
        cleanExternalCache(context);
        cleanExternalFilesDir(context);
    }

    /**
     * 创建指定文件夹
     * @param folderName
     */
    public static String createFolder(Context context, String folderName) {
        File filedir = new File(context.getFilesDir() + folderName);
        if(!filedir.exists()) {
            filedir.mkdirs();
        }
        Log.i(TAG, filedir.getName()+" create folder success.");
        return filedir.getPath();
    }

    /**
     * 保存图片
     *
     * @param parentDir 父目录
     * @param bitmap   图片资源
     * @param fileName 图片文件名
     * @return 图片路径
     */
    public static String saveBitmap(Bitmap bitmap, String parentDir, String fileName) {
        if (bitmap == null || TextUtils.isEmpty(fileName) || parentDir == null) {
            return "";
        }

        File parent = new File(parentDir);
        if(!parent.exists()){
            parent.mkdirs();
        }
        FileOutputStream out = null;
        try {
            File file = new File(parentDir+"/", fileName + ".jpg");//若存视频截图为png格式会花屏
            file.deleteOnExit();
            file.createNewFile();
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

            bitmap.recycle();
            System.gc();
            return file.getPath();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取文件夹大小 （递归耗时）
     */
    public static long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
     */
    public static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }


    /**
     * 清除/data/data/com.xxx.xxx/files下的内容
     */
    public static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
     */
    public static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }

    /**
     * 清除外部files下的内容(/mnt/sdcard/android/data/com.xxx.xxx/files)
     */
    public static void cleanExternalFilesDir(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalFilesDir(null));
        }
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的所以文件及文件夹，如果传入的directory是个文件，将不做处理
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                if (item.isDirectory() && (item.listFiles() != null && item.listFiles().length != 0) ) {
                    // 非空文件夹，递归处理
                    deleteFilesByDirectory(item);
                } else {
                    item.delete();
                }
            }
        }
    }

}
